/*
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2024-10-11 16:39:33
 * @LastEditTime: 2024-11-19 10:58:33
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 文件操作
 * @FilePath: \markdown-magic\src\utils\fs.js
 * @Copyright 版权声明
 */
import { readDir } from '@tauri-apps/plugin-fs'
import { extname } from '@tauri-apps/api/path'

/**
 * 获取目录树
 * @param {String} path 
 * @returns Promise(Array)
 */
export const getDirectoryTree = async (path) => {
  let tree = [];
  return new Promise(async (resolve) => {
    const items = await readDir(path)
    for (let item of items) {
      let fullPath = path + '/' + item.name;
      let isDirectory = item.isDirectory
      let isFile = item.isFile
  
      if (isDirectory === true) {
        let dirTree = {
          name: item.name,
          type: 'directory',
          path: fullPath,
          children: await getDirectoryTree(fullPath)
        };
        tree.push(dirTree)
      }
      if (isFile === true) {
        const extList = ['md', 'markdown', 'mmd', 'mdwn', 'mdown']
        const extName = await extname(fullPath)
        if (extList.includes(extName)) {
          let fileInfo = {
            name: item.name,
            type: 'file',
            path: fullPath
          }
          tree.push(fileInfo)
        } else {
          continue
        }
      }
    }
    resolve(tree)
  })
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 */
export const resolveBlob = (res) => {
  const blob = new Blob([res.data])
  const downloadElement = document.createElement('a')
  const href = window.URL.createObjectURL(blob)
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition'])
  // debugger
  var result = patt.exec(contentDisposition)
  if (result === null) {
    result = contentDisposition.match(
      /filename=(.*)/
    )
  }
  // console.log('contentDisposition--', contentDisposition)
  // console.log('reuslt--', result)
  var fileName = result[1]
  fileName = fileName.replace(/\"/g, '')
  //后台再header中传文件名
  const name = fileName
  downloadElement.href = href
  downloadElement.download = name
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
}
